package cc.customer.bigEmport.services.imp;

import cc.customer.bigEmport.damain.BigEmp;
import cc.customer.bigEmport.damain.EpRecords;
import cc.customer.bigEmport.damain.EprRecords;
import cc.customer.bigEmport.dao.BigEmpMapper;
import cc.customer.bigEmport.dao.EprRecordsMapper;
import cc.customer.bigEmport.services.BigEmpRecords;
import cc.customer.bigEmport.services.BigEmpServices;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service("bigEmpRecordsServices")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class BigEmpRecordsImp extends BaseService<EpRecords> implements BigEmpRecords {

    private static  final Logger logger = LoggerFactory.getLogger(BigEmpRecordsImp.class);

    @Autowired
    private BigEmpServices bigEmpServices;

    @Autowired
    private EprRecordsMapper recordsMapper;

    @Override
    public List<EpRecords> getAllBigEmpRecords(EpRecords records) {

        try {
            Example example = new Example(EpRecords.class);
            Example.Criteria  criteria = example.createCriteria();

            if (!StringUtils.isEmpty(records.getEpBatch())){
                criteria.andLike("epBatch","%"+records.getEpBatch()+"%");
            }
            if (!StringUtils.isEmpty(records.getEpDirector())){
                criteria.andLike("epDirector","%"+records.getEpDirector()+"%");
            }
            if (!StringUtils.isAnyEmpty(records.getStartTimer(),records.getEndTimer())){
                criteria.andBetween("epTime",records.getStartTimer(),records.getEndTimer()+" 23:59:59");

            }else if (!StringUtils.isEmpty(records.getStartTimer())){
                criteria.andCondition("epTime = ",records.getStartTimer());
            }
            /**是否结算**/
            if(!StringUtils.isEmpty(records.getEpBalanceOver())){
                if("2".equals(records.getEpBalanceOver())){
                    criteria.andEqualTo("epBalanceIsbalan","1");
                }else{
                    criteria.andEqualTo("epBalanceOver",records.getEpBalanceOver()).andNotEqualTo("epBalanceIsbalan","1");
                }
            }
            List<String> list = Arrays.asList(Constant.BIGEMP_RESOURCE_TYPE);
            criteria.andIn("epType",list);//andCondition("ep_type = ","1");
            criteria.andEqualTo("epDtype",Constant.ZIYUAN_TYPE_SCHOLLE);
            example.setOrderByClause("ep_time desc");
            List<EpRecords> recordss = this.selectByExample(example);
            return recordss;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取大资源导入记录失败："+e.getMessage());
        }
        return new ArrayList<>();
    }

    @Override
    public List<EpRecords> getAllAiEmpRecords(EpRecords records) {
        try {
            Example example = new Example(EpRecords.class);
            Example.Criteria  criteria = example.createCriteria();

            if (!StringUtils.isEmpty(records.getEpBatch())){
                criteria.andLike("epBatch","%"+records.getEpBatch()+"%");
            }
            if (!StringUtils.isEmpty(records.getEpDirector())){
                criteria.andLike("epDirector","%"+records.getEpDirector()+"%");
            }
            if (!StringUtils.isAnyEmpty(records.getStartTimer(),records.getEndTimer())){
                criteria.andBetween("epTime",records.getStartTimer(),records.getEndTimer()+" 23:59:59");

            }else if (!StringUtils.isEmpty(records.getStartTimer())){
                criteria.andCondition("epTime = ",records.getStartTimer());
            }

            List<String> list = Arrays.asList(Constant.BIGEMP_RESOURCE_TYPE);
            criteria.andIn("epType",list);//andCondition("ep_type = ","1");
            criteria.andEqualTo("epDtype",Constant.ZIYUAN_TYPE_EXEMP);
            example.setOrderByClause("ep_time desc");
            List<EpRecords> recordss = this.selectByExample(example);
            return recordss;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取AI资源导入记录失败："+e.getMessage());
        }
        return new ArrayList<>();
    }

    @Override
    public List<EpRecords> getOneFiveEmpRecords(EpRecords recordsd) {
        try {
            Example example = new Example(EpRecords.class);
            Example.Criteria  criteria = example.createCriteria();
            List<String> list = Arrays.asList(Constant.BIGEMP_RESOURCE_TYPE);

            if (!StringUtils.isEmpty(recordsd.getEpDirector())){
                criteria.andLike("epDirector",recordsd.getEpDirector());
            }
            if (!StringUtils.isAnyEmpty(recordsd.getStartTimer(),recordsd.getEndTimer())){
                criteria.andBetween("epTime",recordsd.getStartTimer(),recordsd.getEndTimer()+" 23:59:59");
            }else if (!StringUtils.isEmpty(recordsd.getStartTimer())){
                criteria.andCondition("epTime = ",recordsd.getStartTimer());
            }
            criteria.andIn("epType",list);//andCondition("ep_type = ","1");
            example.setOrderByClause("ep_time desc");
            List<EpRecords> recordss = this.selectByExample(example);
            if (recordss.size()>150){
                return recordss.subList(0,140);
            }
            return recordss;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取大资源导入记录失败："+e.getMessage());
        }
        return new ArrayList<>();
    }
    /**导入批次用户的结算**/
    @Override
    @Transactional
    public ResponseBo balanceEmpRecords(Long epid, String uuid, String user,int num) {
        try {
            //查询已经结算的数量
             EpRecords epRecords = this.selectByKey(Integer.valueOf(epid+""));
            String epBalanceNum = epRecords.getEpBalanceNum();
            int bancale = Integer.valueOf(epBalanceNum);
            //查询所有意向可结算的数量
            List<BigEmp> list = bigEmpServices.findAllBalanceByUuidAndGroup(uuid, Constant.BIGEMP_BANLCE_GROUP);
            if (list!=null){
                //总数量
                int allList = list.size();
                //判断当前所有的客户是不是查过了已经结算的人数 或者 计算当前的结算是不是有效
                if (allList > bancale&& allList>=(num+bancale)){
                    //如果有效  增加结算记录 和重新计算已经结算的数量
                    String Record = epRecords.getEpBalanceRecord();
                    JSONObject object = new JSONObject();
                    object.put("user",user);object.put("num",num);object.put("time", DateUtil.getCurrentDate("yyyy-MM-dd"));

                    if (!StringUtils.isEmpty(Record)){
                        JSONArray json = JSONArray.parseArray(Record);
                        json.add(object);
                        epRecords.setEpBalanceRecord(json.toJSONString());
                    }else{
                        JSONArray json = new JSONArray();
                        json.add(object);
                        epRecords.setEpBalanceRecord(json.toJSONString());
                    }
                    //如果已经完成了所有的结算  那么将不再给与结算的权利
                    if (allList == (num+bancale)){
                        List<BigEmp> listis =bigEmpServices.balanceEmpNoGroup(uuid);
                        if (listis.isEmpty()){
                            epRecords.setEpBalanceOver("1");
                        }
                    }
                    epRecords.setEpBalanceNum(num+bancale+"");
                    this.updateAll(epRecords);
                }else{
                    return ResponseBo.error("当前没有客户结算");
                }
            }else{
                return ResponseBo.error("当前没有客户结算 ");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("结算失败:"+e.getMessage());
            return ResponseBo.error("结算失败 ");
        }
        return ResponseBo.ok("结算成功");
    }

    @Override
    public ResponseBo viewBalanceEmpRecords(Long epid, String uuid) {
        try {
            JSONObject json = new JSONObject();
            //查询所有的记录
            EpRecords epRecords = this.selectByKey(Integer.valueOf(epid+""));
            String record = epRecords.getEpBalanceRecord();
            JSONArray jsonArray = JSONArray.parseArray(record);
            json.put("records",jsonArray);
            //已经结算的总数
            json.put("titlo",epRecords.getEpBalanceNum());
            //不可计算
            List<BigEmp> list = bigEmpServices.findAllBalanceByUuidAndGroup(uuid, Constant.BIGEMP_BANLCE_GROUP_NO);
            json.put("noBalance",list.size());
            // 未筛选
            List<BigEmp> noGroup = bigEmpServices.balanceEmpNoGroup(uuid);
            json.put("wei",noGroup.size());
            //待结算的人数
            List<BigEmp> listAll = bigEmpServices.findAllBalanceByUuidAndGroup(uuid, Constant.BIGEMP_BANLCE_GROUP);
            String num = (listAll.size() - Integer.valueOf(epRecords.getEpBalanceNum()))+"";
            json.put("dai",num);
            return ResponseBo.ok(json);
        }catch (Exception e){
            logger.error("查询结算详情失败:"+e.getMessage());
        }
        return ResponseBo.error("获取详情失败");
    }

    @Override
    public List<EprRecords> exportEprRecordsInfo(String uuid){
        try {
            Example example= new Example(EprRecords.class);
            example.createCriteria().andEqualTo("cEprBacthUuid",uuid);

            return recordsMapper.selectByExample(example);
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
